import json
import re
import random
import json
import re
from django.contrib.auth import logout,login
from django.http import JsonResponse
from django.contrib import auth
from rest_framework.response import Response
from rest_framework.views import APIView
from utils.ten_token import verify_jwt
from apps.users.models import User,Question
# from libs.baidushenhe import tupian
# from libs.qiniuyun import upload


from django.contrib.auth import login, logout
from django_redis import get_redis_connection
from rest_framework.response import Response

from apps.users.models import User, Classes, Student, Question, PK
from utils.pk_token import pk_token, verify_jwt
from utils.phone_code import smscode, phone_code

redis_client = get_redis_connection('code')


#手机号验证码
class PhoneCodeView(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'message': '请输入正确的手机号'}, status=400)
        code = random.randint(100000, 999999)
        # de = phone_code(mobile, code)
        # print(de)
        print(code)
        redis_client.setex('mobile-%s' % mobile, 300, code)
        return Response({'message': '已发送短信！'})


#注册接口
class RegisterView(APIView):
    def post(self, request):
        data = request.data
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        password_confirmation = data.get('confirmPassword')
        speciality = data.get('zy')
        mobile = data.get('phoneNumber')
        mobile_code = data.get('captcha')

        if not all([username, email, password, password_confirmation, speciality, mobile_code,mobile]):
            return Response({'message': '缺少必传参数'}, status=400)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'message': '请输入正确的手机号'}, status=400)
        if password != password_confirmation:
            return Response({'message': '两次输入的密码不一致'}, status=400)
        if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
            return Response({'message': '请输入正确的邮箱'}, status=400)
        sms_code = redis_client.get('mobile-%s' % mobile)
        if sms_code != mobile_code.encode():
            return Response({'message': '验证码错误'}, status=400)
        old_user = User.objects.filter(mobile=mobile)
        if old_user:
            return Response({'message': '该手机号已被注册！'}, status=400)

        try:
            user = User.objects.create_user(username=username, email=email, password=password, mobile=mobile, major=speciality)
            user.save()
        except Exception as e:
            print(e)
            return Response({'message': '注册失败'}, status=400)
        login(request, user)
        token = pk_token.generate_tokens(user.id)
        return Response({'message': '注册成功', 'token': token}, status=200)


#登录接口
class LoginView(APIView):
    def post(self, request):
        data = request.data
        username = data.get('username')
        password = data.get('password')
        mobile = data.get('mobile')
        mobile_code = data.get('yzm4')
        if username and password:
            user = User.objects.filter(username=username).first()
            if user:
                if not user.check_password(password):
                    return Response({'message': '输入密码错误！'}, status=400)
                login(request, user)
                token = pk_token.generate_tokens(user.id)
                return Response({'message': '登录成功', 'token': token}, status=200)
            else:
                return Response({'message': '用户名或密码错误，请确认是否拥有账户！'}, status=400)
        elif mobile and mobile_code:
            user = User.objects.filter(mobile=mobile).first()
            if user:
                sms_code = redis_client.get('mobile-%s' % mobile)
                if sms_code != mobile_code.encode():
                    return Response({'message': '验证码错误'}, status=400)
                login(request, user)
                token = pk_token.generate_tokens(user.id)
                return Response({'message': '登录成功', 'token': token}, status=200)
            else:
                return Response({'message': '用户名或密码错误，请确认是否拥有账户！'}, status=400)
        else:
            return Response({'message': '缺少必传参数'}, status=400)



class UpdatePasswordView(APIView):
    def put(self, request):
        data = request.data
        password = data.get('pwd1')
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)['user_id']
        try:
            user = User.objects.get(id=user_id)
            user.set_password(password)
            user.save()
            logout(request)
            response = Response({'message': '修改成功'}, status=200)
            response.delete_cookie('passwod')
            return response
        except Exception as e:
            print(e)
            return Response({'message': '修改失败'}, status=400)


class LogoutView(APIView):
    def delete(self, request):
        logout(request)
        return Response({'message': '退出成功！'}, status=200)




# 获取个人详情
class UserConter(APIView):
    def get(self,request):
        token = request.headers.get('Authorization')
        user_id = verify_jwt(token)['user_id']
        user = User.objects.filter(id=user_id).first()
        return JsonResponse({"username": user.username,
                             "mobile": user.mobile,
                             "major": user.major,
                             "avatar": user.avatar})

    # 修改个人信息
    def put(self, request):
        token = request.headers.get('Authorization')[4:]
        user_id = verify_jwt(token)["user_id"]
        user = User.objects.filter(id=user_id).first()
        data = request.data
        user.realname = data.get('realname')
        user.sex = data.get('sex')
        if not re.match(r'^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$', data.get('birthday')):
            return JsonResponse({"success": True, 'message': '生日格式错误'})
        else:
            user.birthday = data.get('birthday')
        user.website = data.get('website')
        if not re.match(r'^(http|https)://[^ "]+$', user.website):
            return JsonResponse({"success": True, 'message': '网址格式错误'})
        user.email = data.get('email')
        if not re.match(r'^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$', user.email):
            return JsonResponse({"success": True, 'message': '邮箱格式错误'})
        user.city = data.get('city')
        user.address = data.get('address')
        user.avatar = data.get('avatar')
        if user.mobile == data.get('mobile'):
            pass
        else:
            user2 = User.objects.filter(mobile=data.get('mobile')).first()
            if user2:
                return JsonResponse({"success": True, 'message': '手机号码已存在'})
            else:
                user.mobile = data.get('mobile')
        if not re.match(r'^1[3-9]\d{9}$', data.get('mobile')):
            return JsonResponse({"success": True, 'message': '手机号码格式错误'})
        user.save()
        return Response({"id": user_id,
                         "username": user.username,
                         "mobile": user.mobile,
                         "realname": user.realname,
                         'birthday': user.birthday,
                         "sex": user.sex,
                         "avatar": user.avatar if user.avatar else '',
                         "website": user.website,
                         "email": user.email,
                         "city": user.city,
                         "address": user.address})











